<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb
      separator="/"
      class="u-mb20"
      v-permission="['account_advertiser_page']"
      v-if="['create', 'edit', 'detail'].includes(pageAction)"
    >
      <el-breadcrumb-item>
        <span
          class="c-text-high u-cursor"
          @click="back"
        >广告主账户管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>广告投放资质</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 账号信息 -->
    <SectionContainer class="u-p20 u-mb40">
      <Tabs
        v-if="['edit', 'detail', 'refuse', 'header', 'audit', 'wait'].includes(pageAction)"
        class="u-mb20"
      >
        <TabsItem @click="$router.push({
          name: 'account-advertiser-basic',
          query: {
            ...$route.query,
            query: {
              ...$route.query.query
            }
          }
        })">账户信息</TabsItem>
        <TabsItem is-active>广告投放资质</TabsItem>
      </Tabs>

      <Audit v-if="['detail', 'header', 'refuse', 'audit'].includes(pageAction)">
        <AuditItem
          :class="{
            'c-hint-succ': aptitudeData.auditMap.internalAudit === '已通过',
            'c-hint-warn': aptitudeData.auditMap.internalAudit !== '已通过'
          }"
          :label="getInnerStatusTitle(aptitudeData.auditMap.internalAudit) + ' 内部审核：'"
        >{{aptitudeData.auditMap.internalAudit}}</AuditItem>
        <AuditItem
          v-if="aptitudeData.auditMap.waitAudit || aptitudeData.auditMap.passAudit || aptitudeData.auditMap.unPassAudit"
          class="c-hint-warn"
          label="<i class='el-icon-warning u-fs16 u-vat u-mt3'></i> ADX审核："
        >
          <div v-if="aptitudeData.auditMap.waitAudit">待审核平台：{{aptitudeData.auditMap.waitAudit}}</div>
          <div v-if="aptitudeData.auditMap.passAudit">已通过审核平台：{{aptitudeData.auditMap.passAudit}}</div>
          <div v-if="aptitudeData.auditMap.unPassAudit">未通过审核平台：{{aptitudeData.auditMap.unPassAudit}}</div>
        </AuditItem>
      </Audit>

      <el-form
        label-width="160px"
        :model="aptitudeData"
        ref="aptitudeForm"
      >
        <!--主体资质文件-->
        <SectionTitle class="u-pt20 u-mb30">主体资质文件
          <el-tooltip
            slot="tip"
            class="item"
            effect="dark"
            placement="top"
          >
            <div slot="content">
              1、开通推广账户必须提供的有效资质证明<br>
              2、提交资质为电子版原件或复印件，如是复印件，需手写“与原件一致”字样，并加盖公司红色公章开通推广账户必须提供的有效资质证明
            </div>
            <i class="iconfont iconfont-10 c-hint-major"></i>
          </el-tooltip>
        </SectionTitle>
        <div class="u-pb20">
          <div
            v-for="(item, index) in aptitudeData.list"
            :key="index"
          >
            <el-form-item
              v-show="index < 3"
              :prop="'list.' + index + '.path'"
              :label="item.name"
              :rules="{
                required: true,
                message: item.name + '不能为空',
                trigger: 'change'
              }"
            >
              <PreviewPicture
                v-show="item.path"
                :data="item.preview"
                :disabled="isDisabled()"
                @remove="removeMainAptitude(index)"
              ></PreviewPicture>
              <el-upload
                v-show="!item.path"
                :disabled="isDisabled()"
                class="u-dib"
                :action="`${UPLOAD_BASE_URL}/manage/api/bus/upload/uploadflie?fileGroups=2`"
                :data="{ uuid: index }"
                :headers="{'x-access-token': token}"
                list-type="picture-card"
                :show-file-list="false"
                :before-upload="uploadBefore"
                :on-success="uploadSuccess"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </div>
        </div>

        <!--可选资质文件-->
        <SectionTitle
          class="u-pt30 u-mb30"
          v-if="aptitudeData.list.length > 2"
        >可选资质文件
          <el-tooltip
            slot="tip"
            class="item"
            effect="dark"
            placement="top"
          >
            <div slot="content">
              1、涉及风险较大的行业时，除提供主体资质以外，还需提交此行业管辖机关核发的许可证明等（请联系工作人员确认）<br>
              2、提交资质为电子版原件或复印件，如是复印件，需手写“与原件一致”字样，并加盖公司红色公章
            </div>
            <i class="iconfont iconfont-10 c-hint-major"></i>
          </el-tooltip>
        </SectionTitle>
        <div class="u-pb20">
          <div
            v-for="(item, index) in aptitudeData.list"
            :key="index"
            class="u-w600"
          >
            <el-form-item
              class="u-mb20"
              v-show="index > 2"
              label="可选资质全称"
              :prop="'list.' + index + '.name'"
              :rules="{
                required: true,
                message: '资质全称不能为空',
                trigger: ['blur', 'change']
              }"
            >
              <el-input
                placeholder="请输入资质全称"
                :disabled="isDisabled()"
                v-model="item.name"
                class="u-w350"
              ></el-input>
              <el-button
                class="u-ml10"
                v-show="!isDisabled()"
                @click="removeOptionalAptitudeItem(index)"
              >删除</el-button>
            </el-form-item>
            <el-form-item
              class="u-mb20"
              v-show="index > 2"
              :prop="'list.' + index + '.path'"
              :rules="{
                required: true,
                message: '资质文件不能为空',
                trigger: 'change'
              }"
            >
              <PreviewPicture
                v-show="item.path"
                :data="item.preview"
                :disabled="isDisabled()"
                @remove="removeOptionalAptitude(index)"
              ></PreviewPicture>
              <el-upload
                v-show="!item.path"
                :disabled="isDisabled()"
                class="u-dib"
                :action="`${UPLOAD_BASE_URL}/manage/api/bus/upload/uploadflie?fileGroups=2`"
                :data="{ uuid: index }"
                :headers="{'x-access-token': token}"
                list-type="picture-card"
                :show-file-list="false"
                :before-upload="uploadBefore"
                :on-success="uploadSuccess"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </div>
        </div>
        <el-form-item>
          <el-button
            icon="el-icon-plus"
            v-show="!isDisabled()"
            @click="addOptionalAptitudeItem"
          >添加一项可选资质</el-button>
        </el-form-item>
        <el-form-item>
          <Tip class="u-lh24">
            注：<br>
            1、广告主仅有一次提交审核机会。资质提审后，如需修改资质信息，请联系管理员<br>
            2、广告主账户审核期间无法正常投放广告
          </Tip>
        </el-form-item>
      </el-form>
    </SectionContainer>

    <div
      class="u-affix-bottom u-page-handle"
      v-if="['create', 'edit', 'detail', 'wait'].includes(pageAction)"
    >
      <el-tooltip
        class="item"
        effect="dark"
        placement="top"
        content="注：广告主账户审核期间无法正常投放广告"
      >
        <el-button
          v-if="['create', 'edit', 'wait'].includes(pageAction)"
          type="primary"
          size="small"
          @click="submitAptitude"
        >提交审核</el-button>
      </el-tooltip>
      <el-button
        v-if="['create', 'edit', 'detail'].includes(pageAction)"
        size="small"
        @click="back"
      >返回</el-button>
    </div>
  </div>
</template>

<script>
import SectionTitle from "@/components/section-title";
import SectionContainer from "@/components/section-container";
import Tip from "@/components/tip";
import PreviewPicture from "@/components/preview-picture";
import Tabs from "@/components/tabs";
import TabsItem from "@/components/tabs-item";
import Audit from "./components/audit";
import AuditItem from "./components/audit-item";

import { sessionStorage } from "@/utils";
import {
  fetchAccountAptitude,
  fetchAccountAptitudeAdd,
  fetchAccountAptitudeUpdate
} from "@/api";

export default {
  components: {
    SectionTitle,
    SectionContainer,
    Tip,
    Tabs,
    TabsItem,
    PreviewPicture,
    Audit,
    AuditItem
  },
  data() {
    return {
      pageAction: this.$route.query.action,
      UPLOAD_BASE_URL: process.env.VUE_APP_UPLOAD_BASE_URL,
      token: sessionStorage.get("USER").token,
      aptitudeDefault: [
        {
          preview: [],
          name: "营业执照",
          type: "1",
          path: ""
        },
        {
          preview: [],
          name: "法人身份证",
          type: "2",
          path: ""
        },
        {
          preview: [],
          name: "ICP备案证书",
          type: "3",
          path: ""
        }
      ],
      aptitudeData: {
        auditMap: {},
        list: []
      }
    };
  },
  methods: {
    // 获取内部审核状态title
    getInnerStatusTitle(v) {
      if (v === "已通过") {
        return "<i class='el-icon-success u-fs16 u-vat u-mt3'></i>";
      } else if (v === "审核拒绝") {
        return "<i class='el-icon-warning u-fs16 u-vat u-mt3'></i>";
      }
      return "<i class='el-icon-question u-fs16 u-vat u-mt3'></i>";
    },
    // 是否禁用编辑
    isDisabled() {
      return !["create", "edit", "wait"].includes(this.pageAction);
    },
    fetchAccountAptitude() {
      fetchAccountAptitude({
        query: {
          userId: this.$route.query.userId
        }
      }).then(res => {
        let list = res.data.list;
        if (!list.length) {
          list = this.aptitudeDefault;
        }

        this.aptitudeData = {
          auditMap: res.data.auditMap,
          list: list.map(item => {
            return {
              preview: [{ url: item.path }],
              name: item.name,
              path: item.path,
              type: item.type
            };
          })
        };
      });
    },
    // 获取新建、更新的数据
    getAptitudeData() {
      return this.aptitudeData.list.map(item => {
        let { type, path, name } = item;
        return {
          type,
          path,
          name
        };
      });
    },
    // 提交资质
    submitAptitude() {
      this.$refs.aptitudeForm.validate((valid, params) => {
        if (valid) {
          if (["create", "wait"].includes(this.pageAction)) {
            fetchAccountAptitudeAdd({
              query: {
                userId: this.$route.query.userId
              },
              body: this.getAptitudeData()
            }).then(() => {
              this.$message({
                message: "资质提交成功",
                duration: 1000
              });
              setTimeout(() => {
                this.back();
              }, 1000);
            });
          } else if (["edit"].includes(this.pageAction)) {
            fetchAccountAptitudeUpdate({
              query: {
                userId: this.$route.query.userId
              },
              body: this.getAptitudeData()
            }).then(() => {
              this.$message({
                message: "已提交审核",
                duration: 1000
              });
              setTimeout(() => {
                this.back();
              }, 1000);
            });
          }
        } else {
          this.$message({
            type: "error",
            message: params[Object.keys(params)[0]][0].message,
            duration: 1000
          });
        }
      });
    },
    // 上传验证
    uploadBefore(file) {
      let size = file.size / 1024 / 1024; // 小于1MB
      let type = ["image/jpeg", "image/png"].includes(file.type); // jpg、png
      if (!size) {
        this.$message.error("文件大小不能超过10MB！");
      }
      if (!type) {
        this.$message.error("只能上传JPG、PNG格式文件！");
      }
      return size && type;
    },
    // 上传成功
    uploadSuccess(res) {
      let { uploadUrl, uuid } = res.data;
      this.aptitudeData.list[uuid].path = uploadUrl;
      this.aptitudeData.list[uuid].preview = [{ url: uploadUrl }];
      this.$refs.aptitudeForm.validateField(`list.${uuid}.path`);
    },
    // 添加可选资质
    addOptionalAptitudeItem() {
      this.aptitudeData.list.push({
        preview: [],
        name: "",
        type: "4",
        path: ""
      });
    },
    // 删除主要资质
    removeMainAptitude(index) {
      this.aptitudeData.list[index].path = "";
      this.$refs.aptitudeForm.validateField(`list.${index}.path`);
    },
    // 删除可选资质
    removeOptionalAptitudeItem(index) {
      this.aptitudeData.list.splice(index, 1);
    },
    removeOptionalAptitude(index) {
      this.aptitudeData.list[index].preview = [];
      this.aptitudeData.list[index].path = "";
      this.$refs.aptitudeForm.validateField(`list.${index}.path`);
    },
    // 返回
    back() {
      this.$router.replace({
        name: "account-advertiser-man",
        query: {
          ...this.$route.query.query
        }
      });
    }
  },
  created() {
    if (this.pageAction === "create") {
      this.aptitudeData.list = this.aptitudeDefault;
    } else {
      this.fetchAccountAptitude();
    }
  }
};
</script>